
import uuid
from datetime import timedelta
from sqlalchemy import select
from model.entitys import User
from initialization import ACCESS_TOKEN_EXPIRE_MINUTES
from utils.tokenUtil import create_access_token

async def login(session, userInfo):
    user_id = ""

    try:
        # 查询用户是否存在
        u = (await session.execute(select(User).filter(User.username==userInfo.username))).scalars().first()

        if u == None:
            u = User()
            u.id = uuid.uuid1().__str__()
            u.nickname = userInfo.username
            u.username = userInfo.username
            u.password = userInfo.password
            session.add(u)

            user_id = u.id

        else:
            # 验证用户账号密码是否正确
            if userInfo.password != u.password:
                return {
                    "message": "密码错误",
                    "code": "400",
                    "data": None
                }

            user_id = u.id

    except Exception as e:
        await session.rollback()
        await session.close()

        return {"message": "数据库操作失败", "code": 500, "errors": e}
    else:
        await session.commit()
    finally:
        await session.close()

    # 如果用户正确通过 则生成token
    # 设置过期时间
    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)

    # 登录token 只存放了user.id
    return {
        "message": "登录成功",
        "code": "200",
        "data": {"token_info": await create_access_token(user_id, expires_delta=access_token_expires)},
    }















